package com.gofaraway.service.redislock;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author ChenPeng
 * @Date 2024/7/28 13:54
 */
@Component
@Slf4j
public class RedisLock implements Lock {

    @Resource
    private RedissonClient redissonClient;

    @Override
    public boolean tryLock(String lockName, long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException {
        RLock lock = redissonClient.getLock(lockName);
        return lock.tryLock(waitTime, leaseTime, unit);
    }

    @Override
    public void lock(String lockName, long leaseTime, TimeUnit unit) {
        RLock lock = redissonClient.getLock(lockName);
        lock.lock(leaseTime, unit);
    }

    @Override
    public void lock(String lockName) {
        RLock lock = redissonClient.getLock(lockName);
        lock.lock();
    }

    @Override
    public void unlock(String lockName) {
        RLock lock = redissonClient.getLock(lockName);
        try {
            if (lock == null) {
                return;
            }
            // 是否还是锁定状态
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                //是当前执行线程的锁
                lock.unlock();
            }
        } catch (Exception e) {
            log.error("unlock fail...", e);
        }
    }
}
